const express=require("express")
const router=express.Router();
const pool=require("../pool");
//http://localhost:3000/index
//app.use("/index",index)
//   ↓
//http://localhost:3000/index/
router.get("/",(req,res)=>{
  //查询文章列表
  var indexObj={
    swiImg:{},
    hotImg:{},
    ativImg:{},
    newsList:{}
  };
  new Promise((resolve,reject)=>{
    //查询首页banner图片
    var sql=`select * from yhc_index_carousel`;
    pool.query(sql,[],(err,result)=>{
      if(err) console.log(err);
      //res.write(JSON.stringify(result));
      indexObj.swiImg=result;
      resolve(true);
    })
  }).then(value=>{
    //查询热门话题图图片
    return new Promise((resolve,reject)=>{
      var sql=`select * from yhc_index_hot`;
      pool.query(sql,[],(err,result)=>{
        if(err) console.log(err);
        indexObj.hotImg=result;
        //res.end(); 
        resolve(true);
      })
    })
  }).then(value=>{
    //查询热门活动图片
    return new Promise((resolve,reject)=>{
      var sql=`select * from yhc_index_active`;
      pool.query(sql,[],(err,result)=>{
        if(err) console.log(err);
        indexObj.ativImg=result;
        resolve(true);
      })
    })
  }).then(value=>{
    //查询新闻
    return new Promise((resolve,reject)=>{
      //1:参数 pno pageSize
      var pno=req.query.pno;
      var pageSize=req.query.pageSize;
      //2:允许使用默认值  1 7
      if(!pno){pno=1}
      if(!pageSize){pageSize=5}

      var sql = " SELECT did,title,";
          sql+=" dates,pic,comments";
          sql+=" FROM yhc_discover_all";
          sql+=" LIMIT ?,?";
      var ps=parseInt(pageSize);
      var offset=(pno-1)*ps;
      
      pool.query(sql,[offset,ps],(err,result)=>{
        if(err) console.log(err);
        indexObj.newsList=result;
        res.send(JSON.stringify(indexObj)); 
        res.end();
      })
    })
  }).catch(err=>{
    throw new Error(err);  //当catch中new Error时，后面的then不会执行(绕过)
  })
  
})

module.exports=router;